package com.naiterui.ehp.bs.patient.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.NonUniqueResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.naiterui.ehp.bp.domain.DrMessageConsultOrder;
import com.naiterui.ehp.bs.patient.dao.IDrMessageConsultOrderDao;
import com.naiterui.ehp.bs.patient.repository.IApDrMessageConsultOrderRepository;

@Component
public class ApDrMessageConsultOrderDaoImpl implements IDrMessageConsultOrderDao {

    @Autowired
    private IApDrMessageConsultOrderRepository drMessageConsultOrderRepository;

    @Override
    public void saveOrUpdate(DrMessageConsultOrder consultOrder) {
        if (consultOrder.getId() == null) {
            consultOrder.setCreatedAt(new Date());
            consultOrder.setCreatedBy("system");
        } else {
            consultOrder.setChangedAt(new Date());
            consultOrder.setChangedBy("system");
        }
        drMessageConsultOrderRepository.saveOrUpdate(consultOrder);
    }

    @Override
    public DrMessageConsultOrder findByPatientAndDoctorAndPayStatus(Long patientId, Long doctorId, Integer payStatus) {
        List<DrMessageConsultOrder> list = drMessageConsultOrderRepository.findByPatientIdAndDoctorIdAndPayStatus(patientId, doctorId, payStatus);
        int size = list.size();
        if (size == 1) {
            return list.get(0);
        } else if (size > 1) {
            throw new NonUniqueResultException(size);
        } else {
            return null;
        }
    }

    @Override
    public DrMessageConsultOrder findOrderByPatientAndDoctorAndConsultSessionStatus(Long patientId, Long doctorId, Integer consultSessionStatus) {
        DrMessageConsultOrder result = drMessageConsultOrderRepository.findFirstByPatientIdAndDoctorIdAndConsultSessionStatus(patientId,
                doctorId, consultSessionStatus);
        return result;
    }

    @Override
    public DrMessageConsultOrder findMessageConsultOrderByOrderSn(String orderSn) {
        DrMessageConsultOrder result = drMessageConsultOrderRepository.findFirstByOrderSn(orderSn);
        return result;
    }

    @Override
    public DrMessageConsultOrder getBySessionId(Long patientId, Long doctorId, String sessionId) {
        return drMessageConsultOrderRepository.findFirstByPatientIdAndDoctorIdAndSessionId(patientId, doctorId, sessionId);
    }

    @Override
    public DrMessageConsultOrder update(DrMessageConsultOrder messageConsultOrder) {
        return drMessageConsultOrderRepository.update(messageConsultOrder);
    }
}
